package com.distributeredis.redis_springboot.springaop;

import com.distributeredis.redis_springboot.springaop.impl.LogServiceImpl;
import com.distributeredis.redis_springboot.springaop.vo.User;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

//@Slf4j
//@Component
//@Aspect
public class MyLogAspect {

    @Autowired
    private LogServiceImpl logService;
    // 定义一个切入点
    @Pointcut("@annotation(com.distributeredis.redis_springboot.springaop.MyOperationLog)")
    public void pt(){}

    // 定义一个通知
    @Around("pt()")
    public Object deAround(ProceedingJoinPoint joinPoint) {
        Object proceed = null;
        // 获取参数
        Object[] args = joinPoint.getArgs();
        // 获取签名
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature)signature;
        Method methodNam = methodSignature.getMethod();
        String methodNamName = methodNam.getName();

        String signa = joinPoint.getSignature().toString();

        // 获取方法名
        String methodName = signa.substring(signa.lastIndexOf(".") + 1, signa.indexOf("("));
        String methodName1 = joinPoint.getSignature().getName();
        // 获取目标类的名称
        String classType = joinPoint.getTarget().getClass().getName();
        try {
            Class<?> aClass = Class.forName(classType);
            Method[] declaredMethods = aClass.getDeclaredMethods();
            for (Method method : declaredMethods) {
                if(method.isAnnotationPresent(MyOperationLog.class)) {
                    // 获取这个注解的属性信息
                    MyOperationLog myOperationLog = method.getAnnotation(MyOperationLog.class);
                    // 取出注解上的属性字段内容
                    String currentUser = myOperationLog.currentUser();
                    String operate = myOperationLog.operate();

                    // 执行业务逻辑
                    args[0] = new User().setName("李四").setAge("22");
                    proceed = joinPoint.proceed(args);

                }
            }
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
        return proceed;
    }
}
